/**
 * Created by Administrator on 2018/5/17.
 */


define(function (require,exports,module) {
    var sTpl = require("./fboUserMgr.html");
    require("./fboUserMgr.css")

    var VueComponent = Vue.extend({
        template: sTpl
        ,methods:{
            filterRoles:function(key,data){
                if(!key){
                    return true;
                }
                if(data.code && data.code.indexOf(key) >=0){
                    return true;
                }
                if(data.label && data.label.indexOf(key) >= 0){
                    return true;
                }
                if(data.teamName && data.teamName.indexOf(key) >= 0){
                    return true;
                }
                return false;
            },
            clearData:function(){
                this.formData = {
                    userName:"",
                    newPwd:"",
                    userCnName:"",
                    phone:"",
                    email:"",
                    userStatus:true
                }
            },
            getContextPath:function(){
                var contextPath = document.location.pathname;
                var contextPath = contextPath.split('/')[1];
                var contextPath = "/"+contextPath;
                this.contextPath = contextPath;
                $('.el-table__row:first').click();
            },
            onSearchFwUser: function(val){
                var   searchVal =this.formInput.key||"";
                this.urls.url =this.contextPath+this.urls.initurl+"?key="+searchVal+"&";
            },
            handlerAddRole:function(){
            },

            handlerLoadRole:function(){
                this.selectRoleVal=[];
                this.userRoleTransfer=[];
                var self =this;
                var naldata = this.$refs.userRoleTable.$data.internalData;
                //从表格中获取已授权的角色
                for(i=0;i<naldata.length;i++){
                    var jftp = {resId:naldata[i].resId,serverName:naldata[i].serverName,serverCnName:naldata[i].serverCnName};
                    this.selectFtpVal.push(jftp);
                }
                //加载系统全部角色
                axios.get(this.contextPath+'/api/webframe/fwrole?type=0').then(function(result){
                    for(i=0;i<result.data.content.length;i++){
                        var temp = result.data.content[i];
                        self.userRoleTransfer.push({resId:temp.ftpId,serverName:temp.serverName,serverCnName:temp.serverCnName});
                    }
                    this.dialogTransferFtpVisible=true;
                }.bind(this));
            },
            addFwUser:function(){
                this.disabledBtn = false;
                $('.el-input__inner').val('');
                this.rules.newPwd=[
                    {required: true, message: '请输入密码', trigger: 'blue'}
                    // ,{min: 8, /*max: 15,*/ message: '长度在 8 到 15 个字符', trigger: 'blur'}
                ];
                this.clearData();
                this.userFormTitle = "新增用户";
                this.$refs.table.dialogFormVisible=true;

            },
            userRowClick:function(row, event, column){
                this.$refs.table.internalData.forEach(function (data) {
                    data.checked=false;
                })
                row.checked=true;
                if(this.currentuserId != row.userId){
                    this.disableRowBtn = false;
                    this.currentuserId = row.userId;
                    this.internalData = [row];
                    this.initUserRole();
                }
                //this.initUserRolesAndTeams();
            },
            editFwUser:function(index,val){
                if(this.singleSelect()){
                    this.disabledBtn = false;
                    this.rules.newPwd=[
                        // {min: 8, max: 15, message: '长度在 8 到 15 个字符', trigger: 'blur'}
                    ];
                    this.formData = $.extend(true,{},this.internalData[0]);
                    this.formData.userStatus = this.formData.userStatus==1;
                    this.userFormTitle = "修改用户";
                    this.$refs.table.dialogFormVisible=true;
                }
            },
            editUserRoles:function(){
                this.dialogTransferRoleVisible = true;
                this.transferUserRoleTransfer = $.extend(true,[],
                    this.userRoleTransfer.sort(function(a,b){
                        a.teamName= a.teamName==null?"":a.teamName;
                        b.teamName= b.teamName==null?"":b.teamName;
                        return a.teamName>b.teamName;
                    }));
                this.transferSelectRoleVal = $.extend(true,[],
                    this.selectRoleVal.sort(function(a,b){
                        a.teamName= a.teamName==null?"":a.teamName;
                        b.teamName= b.teamName==null?"":b.teamName;
                        return a.teamName>b.teamName;
                    }));
            },
            selectionChange:function(val){
                this.internalData = val;
            },
            singleSelect:function(){
                if(this.internalData.length!=1){
                    this.$message({   type: 'error',   message: '请选择一条记录!'
                    });
                    return false;
                }
                return true;
            },
            formCancle:function(){
                this.$refs.table.dialogFormVisible=false;
            },
            formConfirm:function(){
                var self = this;
                if(self.disabledBtn){
                    return;
                }else{
                    self.disabledBtn = true;
                }
                this.$refs.editForm.validate(function (valid) {
                    if(!valid){
                        self.disabledBtn = false;
                        return;
                    }
                    var formData = $.extend(true,{},self.formData);
                    formData.userStatus = formData.userStatus?"1":"0";
                    axios({
                        method:self.formData.userId ? "put" : "post",
                        url:self.contextPath+self.urls.initurl,
                        data:formData,
                    }).then(function(response){
                        self.disabledBtn = false;
                        self.$message.success("保存成功");
                        self.$refs.table.dialogFormVisible=false;
                        self.$refs.table.freshTableList();
                        self.disableRowBtn = true;
                    }).catch(function(e){
                        self.disabledBtn = false;
                        self.$message.error(e.data.errorMsg || "保存失败");
                    });
                    //self.$refs.table.dialogFormVisible=false;
                    //self.formData.userStatus = self.formData.userStatus?"1":"0";
                    //self.$refs.table.updateData(self.contextPath+self.urls.initurl,self.formData);
                });
            },
            handleCloseTeam:function(){
                self.$data.dialogVisible2 = false;
            },
            handleChange:function(){
                return;
            },
            initUserRole:function(){
                var self=this;
                axios.get(this.contextPath+'/api/webframe/fwrole/transferByUser/'+this.currentuserId).then(function(result){
                    var allroles =result.data.dataRoles || [];
                    var myuroles=result.data.myRoles;
                    var noselec = [];
                    if(myuroles !=null && myuroles.length > 0){
                        var chooserole = [];
                        var selectedRoleIds = {};
                        for(var i in myuroles){
                            selectedRoleIds[myuroles[i]] = true;
                        }
                        for(var i in allroles){
                            var roleInfo = allroles[i];
                            var key = roleInfo.key;
                            if(selectedRoleIds[key]){
                                chooserole.push(roleInfo);
                            }else{
                                noselec.push(roleInfo);
                            }
                        }
                        self.selectRoleVal=chooserole;
                        self.userRoleTransfer = allroles;
                        //self.userRoleTransfer = noselec;
                    }else{
                        self.selectRoleVal=[];
                        self.userRoleTransfer = allroles;
                    }
                });
            },

            initUserRolesAndTeams:function(){
                var contextPath = this.contextPath;
                var userId = this.$data.internalData[0].userId+"";
                axios.get(this.contextPath+'/api/webframe/fwteam/transferByUser/'+userId).then(function(result){
                    this.$data.dataTeams=result.data.dataTeams;
                    this.$data.myTeams=result.data.myTeams;
                }.bind(this));
            },
            confirmRoles:function(){
                this.dialogTransferRoleVisible = false;
                var roleId = [];
                for(var i=0;i<this.transferSelectRoleVal.length;i++){
                    roleId[i]=this.transferSelectRoleVal[i].key;
                }
                var data = {
                    "roleIds":roleId,
                    "userId":this.currentuserId
                }
                var self = this;
                axios.post(this.contextPath+'/api/webframe/fwrole/updateFwRoleUserByUserId',data).then(function(result){
                    self.$message({type:"success",message:"角色分配成功！"});
                    self.selectRoleVal = self.transferSelectRoleVal;
                });
            },
            confirmTeams:function(){
                this.dialogVisible2 = false
                var data = {
                    "teamIds":this.$data.myTeams,
                    "userId":this.$data.internalData[0].userId+""
                }
                var contextPath = this.contextPath;
                axios.post(contextPath+'/api/webframe/fwteam/updateFwTeamUserByUserId',data).then(function(result){
                    console.log('confirmRoles ok')
                }.bind(this));
            }

        },
        mounted:function() {
            setTimeout(function(){
                $('.el-table__row:first').click();
            },100);
        }
        ,data:function(){
            var validatePass2 = function(rule, value, callback)  {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.formData.newPwd) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                userFormTitle:"",
                disableRowBtn:true,
                disabledBtn:false,
                contextPath:"",
                formInput:{user:""},
                formLabelWidth: '120px',
                formData: {},
                internalData: [],
                activeNames:['1','2'],
                myRoles:[],
                dataRoles:[],
                myTeams:[],
                dataTeams:[],
                userRoleTransfer:[],
                selectRoleVal:[],
                transferUserRoleTransfer:[],
                transferSelectRoleVal:[],
                currentuserId:'',
                dialogTransferRoleVisible:false,
                dialogVisible:false,
                dialogVisible2:false,
                urls:{
                    url:this.contextPath+"/api/webframe/fwuser",
                    initurl:"/api/webframe/fwuser"
                },
                rules: {
                    userName: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 3, max: 32, message: '长度在 3 到 32 个字符', trigger: 'blur'}
                    ],
                    newPwd: [
                        {required: true, message: '请输入密码', trigger: 'blur'}
                        //, {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
                    ],
                    /*userPwd2: [
                     { validator: validatePass2, trigger: 'blur' }
                     ],*/
                    userCnName: [
                        {required: true, message: '请输入中文名', trigger: 'blur'},
                        {min: 2, /*max: 32,*/ message: '长度在 2 到 32 个字符', trigger: 'blur'}
                    ],
                    phone: [
                        {required: true, message: '请输入联系电话', trigger: 'blur'},
                        {/*min: 11, max: 11,*/ message: '长度11个字符', trigger: 'blur'}
                    ],
                    email: [
                        {required: false, message: '请输入电子邮箱', trigger: 'blur'}
                    ]
                }
            }
        },
        created:function (){
            this.getContextPath();
            this.urls.url = this.contextPath+"/api/webframe/fwuser/?key=";
            this.clearData();
            window.self = this;

        },
        activated:function () {
            messages.$emit('change','用户管理');
        },
        filters: {
            roleFilter:function(items){
                var result = [];
                if(items.length > 0){
                    $.each(items,function(index,item){
                        if(window.self.$data.myRoles.indexOf(item.key) != -1){
                            result.push(item);
                        }
                    });
                }
                return result;
            },
            teamFilter:function(items){
                var result = [];
                if(items.length > 0){
                    $.each(items,function(index,item){
                        if(window.self.$data.myTeams.indexOf(item.key) != -1){
                            result.push(item);
                        }
                    });
                }
                return result;
            }
        },
    });
    module.exports = VueComponent;
})

